package com.castudio.Controller;


import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.castudio.COS.qiniu.service.QiNiuService;
import com.castudio.Entity.Activity;
import com.castudio.Filter.R;
import com.castudio.Filter.Result;
import com.castudio.Service.ActivityService;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 小陈同学
 * @since 2023-01-19
 */

@RestController
@RequestMapping("/activity")
public class ActivityController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private ActivityService activityService;

    @Autowired
    private QiNiuService qiNiuService;

    @GetMapping("/all")
    public List<Activity> listAll() {
        return activityService.list();
    }

    /*新增*/
    @PostMapping("/add")
    public Result add(@RequestBody Activity activity) {

        return activityService.save(activity) ? Result.success() : Result.failure();

    }

    /*更新*/
    @PostMapping("/update")
    public Result update(@RequestBody Activity activity) {

        return activityService.updateById(activity) ? Result.success() : Result.failure();

    }

    /*新增或者更新*/
    @PostMapping("/AddOrUpdate")
    public Result AddOrUpdate(@RequestBody Activity activity) {

        return activityService.saveOrUpdate(activity) ? Result.success() : Result.failure();

    }

    /*删除*/
    @PostMapping("/delete")
    public Result delete(Integer id) {

        return activityService.removeById(id) ? Result.success() : Result.failure();

    }

    /*模糊查询*/
    @PostMapping("/Obscure")
    public Result Obscure(@RequestBody Activity activity) {

        LambdaQueryWrapper<Activity> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.isNotBlank(activity.getTitle())) {
            queryWrapper.like(Activity::getTitle, activity.getTitle());
        }
        return Result.success(activityService.list(queryWrapper));
    }

    /*分页*/
/*    @PostMapping("/page/")
    public RespPageEntity getAllActivities(@RequestParam(defaultValue = "1")Integer page,
                                           @RequestParam(defaultValue = "20")Integer size,
                                           @RequestParam(defaultValue = "")String title){

        return activityService.getAllActivities(page, size, title);

    }*/
    @GetMapping("/{currentPage}/{PageSize}")
    public R getPage(@PathVariable Integer currentPage, @PathVariable Integer PageSize, Activity activity) {
        IPage<Activity> page = activityService.getPage(currentPage, PageSize, activity);
        //如果当前页码之大于总页码值，重新执行查询操作，使用最大页码作为当前页码值
        if (currentPage > page.getPages())//如果当前页码之大于总页码值
            page = activityService.getPage((int) page.getPages(), PageSize);//使用最大页码作为当前页码值
        return new R(true, page);
    }

    /*主要内容上传*/
    @ApiOperation(value = "上传文件,form-data当时,传值file", notes = "上传文件,form-data方式,传值file")
    @PostMapping("/uploadFile")
    public JSONObject uploadFile(HttpServletRequest req, HttpServletResponse res) {

        JSONObject data = new JSONObject();
        try {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            MultipartFile file = mreq.getFile("file");

            if (file.getSize() == 1) {
                String path = "/CAStudio";
                // String fileUrl = COSConfig.uploadFile(file, path, req.getServletContext());
                InputStream inputStream = file.getInputStream();

                // 以下为七牛云多文件上传方法
                String fileUrl = qiNiuService.uploadFile(inputStream , path);

                /*获得前端数据*/
                String title = req.getParameter("title");
                String profile = req.getParameter("profile");
                String categories = req.getParameter("categories");
                String author = req.getParameter("author");
                String content = req.getParameter("content");

                data.put("code", 200);
                data.put("msg", "上传成功");
                data.put("fileUrl", fileUrl);
                System.out.println(fileUrl);
                System.out.println(title);
                System.out.println(profile);
                System.out.println(categories);
                System.out.println(author);
                System.out.println(content);

                activityService.save(fileUrl, title, categories, profile, author, content);

                return data;
            } else {
                data.put("code", 400);
                data.put("msg", "请上传文件");
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            data.put("code", 500);
            data.put("msg", "网络开小差了");
            return data;
        }

    }

    /*图像上传*/
    /*@ApiOperation(value = "上传文件,form-data当时,传值file", notes = "上传文件,form-data方式,传值file")
    @PostMapping("/uploadImage")
    public JSONObject uploadImage(HttpServletRequest req, HttpServletResponse res) {

        JSONObject data = new JSONObject();
        try {
            MultipartHttpServletRequest mreq = (MultipartHttpServletRequest) req;
            MultipartFile Image = mreq.getFile("Image");
            if (Image.getSize() > 0) {
                String path = "/CAStudio";
                String image = COSConfig.uploadFile(Image, path, req.getServletContext());
                data.put("code", 200);
                data.put("msg", "上传成功");
                data.put("image", image);
                System.out.println(image);
                activityService.saveImage(image);
                return data;
            } else {
                data.put("code", 400);
                data.put("msg", "请上传文件");
                return data;
            }
        } catch (Exception e) {
            e.printStackTrace();
            logger.error(e.getMessage());
            data.put("code", 500);
            data.put("msg", "网络开小差了");
            return data;
        }

    }*/

}
